<template>
  <px-dialog v-model="dialogVisible" width="60%" align-center>
    <template #header>
      <div class="my-header">
        <h4>
          <div class="title-content">预览“{{ data?.tableName }}”</div>
        </h4>
      </div>
    </template>
    <px-scrollbar id="print-content" class="preview-container">
      <div v-for="(item, index) in sheetList" v-show="item.isSelected" :key="index" class="excelTable" v-html="item.content" />
    </px-scrollbar>
  </px-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import * as XLSX from "xlsx/xlsx.mjs";
import { getToken } from "@/utils/auth";
import { PxMessage } from "px-ui";
import axios from "axios";
const props = defineProps(["data"]);
const dialogVisible = defineModel("dialogVisible");
const sheetList = ref([]);
watch(
  () => [props.data?.attachment, dialogVisible],
  () => {
    if (props.data?.attachment && dialogVisible.value) {
      getData();
    }
  }
);
const getData = () => {
  sheetList.value = [];
  axios({
    method: "post",
    url: "/ifp/sharing/api/v1/file/download",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + getToken().accessToken || "",
      facCode: localStorage.getItem("facCode") || ""
    },
    data: {
      id: props.data.attachment
    },
    responseType: "arraybuffer"
  }).then(res => {
    let workbook = XLSX.read(res.data, { type: "binary" });
    try {
      const env = new TextDecoder();
      const unit_msg = new Uint8Array(res.data);
      const resData = JSON.parse(env.decode(unit_msg));
      if (!resData.success) {
        PxMessage.error(resData.msg);
      }
    } catch (error) {}
    let sheetFileList = workbook.SheetNames;
    sheetFileList.forEach((item, index) => {
      let ws = workbook.Sheets[item];
      let fileContent = "";
      try {
        // 把excel文件流转化为html字符串，以便于v-html使用
        fileContent = XLSX.utils.sheet_to_html(ws);
      } catch (error) {
        console.error("xlsx", error);
      }
      sheetList.value.push({
        name: item,
        isSelected: index == 0,
        content: fileContent
      });
    });
  });
};
const getDataByNewQuery = () => {};
</script>

<style lang="scss" scoped>
.preview-container {
  height: calc(100vh - 158px);
  // overflow-y: auto;
}
.my-header {
  padding-right: 30px;
}
.title-content {
  height: 24px;
  font-size: 16px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.8);
  line-height: 24px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
:deep(.excelTable) {
  table {
    min-width: 100%;
    border-collapse: collapse !important;
    background-color: #fff;
    border: 1px solid #000;

    td {
      padding: 12px;
      font-size: 14px;
      color: #666;
      word-break: keep-all;
      white-space: nowrap;
      border: 1px solid #000;
    }
  }
}
</style>
